define(function(require, exports, module) {
    'use strict';
    
    var rk = require('./rk');
    rk.oa = {};
    (function() {
        var urlmap = {
            workreport: {
                'init': '/json/oa_workreport/init-report-list.action',
                'mine': '/json/oa_workreport/list-my-submitted.action',
                'received': '/json/oa_workreport/list-submitted-to-myself.action',
                'subordinate': '/json/oa_workreport/list-group-submitted.action',
                'opencreate': '/json/oa_workreport/open-create.action',
                'openupdate': '/json/oa_workreport/open-update.action',
                'update': '/json/oa_workreport/update.action',
                'save': '/json/oa_workreport/save.action'
            },
            approval: {},
            notice: {}
        };
        $.extend(rk.oa, {
            //写法1：rk.oa.getRequestUrl('workreport.init'); 返回 '/json/sns_workreport/init-report-list.action'
            //写法2：rk.oa.getRequestUrl('workreport', 'init'); 返回 '/json/sns_workreport/init-report-list.action'
            getRequestUrl: function(arg0, arg1) {
                var appName; //like: 'workreport'
                var key; //like: 'init'
                if (arg0 && arg0.indexOf('.')) {
                    var arr = arg0.split('.');
                    appName = arr[0];
                    key = arr[1];
                } else if (typeof arg1 != 'undefined') {
                    appName = arg0;
                    key = arg1;
                }
                var map = urlmap[appName];
                if (map) return map[key];
            }
        });
    })();
    (function() {
        var panelSel = '#oa_panel';
        var panelContentSel = '#pagecontent >.wrapper-panel-inner> .oa-panel';
        var contentSel = '#oa_content';
        var shadeSel = '#oa-shade';
        var content_resize_inited = false;
        var curtain_resize_inited = false;
        var resize_timer;
        $.extend(rk.oa, {
            showApp: function(appFullName, opt, ctrlOpt){
                $('#oamenubar').pageOAMenuCtrl('click', appFullName, opt, ctrlOpt);
            },
            popupMenu: function(){
                $('#oamenubar').pageOAMenuCtrl('openMenu');
            },
            //获得Panel的dom元素
            getCurtain: function() {
                return rk.oa.getCurtainElem();
            },
            getCurtainElem: function() {
                var oaPanel = rk.oa.getPanelElem();
                return oaPanel ? oaPanel.find('>.oa-curtain') : null;
            },
            //删除OA侧面板第二层遮罩
            closeCurtain: function(opt) {
                var me = this;
                me.removeCurtain(opt);
            },
            removeCurtain: function(opt) {
                if (typeof opt == 'undefined') opt = {};
                var me = this;
                var panelCon = $(panelSel);
                if (panelCon.size() == 0) return;
                var cover = panelCon.find('>.oa-curtain');
                window.setTimeout(function(){
                    $('.ui-effects-wrapper').addClass('oa-curtain-sliding');
                }, 1);
                cover.hide("blind", {
                    direction: "right"
                }, 300, function() {
                    cover.off().remove();
                    if (opt.onSuccess)(opt.onSuccess)();
                });
            },
            //弹出OA侧面板第二层遮罩
            popupCurtain: function(opt) {
                if (typeof opt == 'undefined') opt = {};
                var me = this;
                var panelCon = $(panelSel);
                if (panelCon.size() == 0) return; //遮盖层无法独立于panel存在
                panelCon.find('.oa-curtain').off().remove();
                panelCon.append(rk.templateText(require('../oa/tmpl/tpl_oa_curtain.tpl')));
                var curtain = panelCon.find('>.oa-curtain');
                var curtain_content = curtain.find('>.oa-curtain-box');
                curtain_content.beLoading();
                curtain.find('a[act="close_oa_curtain"]').on('click', function() {
                    rk.oa.removeCurtain();
                });
                if(opt.top){//向下偏移的高度
                    curtain.data('top', opt.top);
                }
                _handleCurtainResize(panelSel);
                window.setTimeout(function(){
                    $('.ui-effects-wrapper').addClass('oa-curtain-sliding');
                }, 1);
                curtain.show("blind", {
                    direction: "right"
                }, 300, function() {
                    if (typeof opt == 'function')(opt)(curtain_content);
                    if (opt.onSuccess)(opt.onSuccess)(curtain_content);
                    _resizeCurtain(panelSel);
                });
            },
            //获得Panel的dom元素
            getPanel: function() {
                return $(panelSel);
            },
            getPanelElem: function() {
                return $(panelSel);
            },
            removePanel: function() {
                var panelCon = $(panelSel);
                if (panelCon.size() > 0) {
                    panelCon.trigger('onPanelClose');
                    panelCon.unbind('onPanelClose');
                    panelCon.off();
                    if (panelCon.destroy) panelCon.destroy();
                    panelCon.remove();
                }
            },
            hidePanel: function(callback) {
                var me = this;
                var panelCon = $(panelSel);
                panelCon.hide();
                panelCon.parent().hide();
                //按钮旋转
                $('#oamenubar').pageOAMenuCtrl('showClosingIcon');
                //阴影
                me._hideShade();
                if (typeof callback != 'undefined')(callback)();
                panelCon.trigger('onPanelHide');
                // return;
                // panelCon.addClass('sb-right');
                // $('#oa_panel').animate({
                //     width: '0px'
                // }, {
                //     duration: 200,
                //     complete: function() {
                //         oaTogger.find('span').addClass('oa-slidebar-taggle').removeClass('oa-slidebar-taggle-open');
                //         me._hideShade();
                //         if (typeof callback != 'undefined')(callback)();
                //         $('#oa_panel').hide()
                //     }
                // });
                //调整微信位置
                _runPrivateMsgMethod('onOAResize', 'oahide');
            },
            showPanel: function(callback) {
                var me = this;
                var panelCon = $(panelSel);
                $('#oa_panel').show().width(400).css('right', '0px');
                panelCon.parent().show();
                _repositionOAStuff();
                //按钮旋转
                $('#oamenubar').pageOAMenuCtrl('showOpeningIcon');
                //panelCon.removeClass('sb-right');
                //阴影
                me._showShade();
                if (typeof callback != 'undefined')(callback)();
                panelCon.trigger('onPanelShow');
                // $('#oa_panel').animate({
                //     width: '400px'
                // }, {
                //     duration: 200,
                //     complete: function() {
                //         oaTogger.find('span').addClass('oa-slidebar-taggle').addClass('oa-slidebar-taggle-open');
                //         panelCon.removeClass('sb-right');
                //         me._showShade();
                //         if (typeof callback != 'undefined')(callback)();
                //     }
                // });
                
                //调整微信位置
                _runPrivateMsgMethod('onOAResize', 'oashow');
            },
            panelIsOpen: function() {
                var me = this;
                return me.getPanelElem().is(':visible');
            },
            panelExist: function() {
                var me = this;
                return me.getPanelElem().size() > 0;
            },
            closePanel: function() {
                var me = this;
                me.hidePanel(function() {
                    $(panelSel).unbind('onPanelHide');
                    me.removePanel();
                    me._hideShade();
                });
                me.closeContent();
            },
            //弹出OA侧面板
            popupPanel: function(opt) {
                if (typeof opt == 'undefined') opt = {};
                var me = this;
                var panelCon = $(panelSel);
                me.removePanel();
                require.async('oa/tmpl/tpl_oa_panel.tpl', function(html) {
                    $(panelContentSel).append(rk.templateText(html));
                    var panelCon = $(panelSel);
                    $(panelContentSel).find('.oa-panel-body').beLoading();
                    me._showShade();
                    me.showPanel(function(){
                        if(opt.onHide) panelCon.bind('onPanelHide', function(){ opt.onHide(); });
                        if(opt.onClose) panelCon.bind('onPanelClose', function(){ opt.onClose(); });
                        if (typeof opt == 'function')(opt)(cover);
                        if (opt.onSysSuccess)(opt.onSysSuccess)(panelSel);
                        if (opt.onSuccess)(opt.onSuccess)(panelSel);
                    });
                    $(panelContentSel).mousedown(function(e){e.stopPropagation()});//防止干扰crm的详情页滑出
                    me.removeContent();
                });
            },
            _hideShade: function() {
                var shade = $(shadeSel);
                shade.hide(); //遮罩
            },
            _showShade: function() {
                var shade = $(shadeSel);
                shade.show(); //遮罩
                if(shade.data('click-inited'))return;
                shade.click(function(){
                    var close = true;
                    var contents = $(document.body).find('>[act="oacontent"]');
                    contents.each(function(i, content){
                        if($(content).is(':visible')) close = false;
                    });
                    if(close) rk.oa.hidePanel();
                }).data('click-inited', true);
                shade.mousedown(function(e){e.stopPropagation()});//防止干扰crm的详情页滑出
            },
            //获得Content的dom元素
            getContent: function() {
                return this.getContentElem();
            },
            getContentElem: function() {
                return $(document.body).find('>[act="oacontent"]:visible');
            },
            //弹出OA内容面板
            popupContent: function(opt) {
                var me = this;
                me.removeContent();
                var html = require('../oa/tmpl/tpl_oa_content.tpl');
                var id = (opt.id ? opt.id : 'oa_content');//如果指定id，则是非普通content，closeContent对其无效。
                html = rk.templateText(html, {id: id});
                var sel = '#' + id;
                $(document.body).append(html);
                var elem = $(sel).find('>.oa-content-detail');
                if(opt.size == 'middle'){
                    $(sel).addClass('oa-content-800');
                }
                $(sel).find('.oa-content-detail:first').beLoading({size: 'large'});
                if (typeof opt == 'function')(opt)(elem);
                if (opt.onSuccess)(opt.onSuccess)(elem);
                _handleContentResize(sel);
                _resizeContent(sel);                
                _repositionOAStuff();
                if(opt.defaultScroll !== false) $(sel).beScroll();
                //按照css要求，生成滚动条后，再追加关闭按钮
                $(sel).prepend('<a href="javascript:;" class="task_right_close">'+rk.i18n('CLOSE')+'</a>');
                $(sel).find('>.task_right_close').on('click', function() {
                    rk.oa.closeContent();
                    if(opt.onCloseClick)(opt.onCloseClick)();
                });
                $('#oa-shade').css('cursor', 'auto');

                //调整微信位置
                _runPrivateMsgMethod('toMin');
            },
            //关闭OA内容面板
            removeContent: function() {
                var me = this;
                $(document.body).find('>[act="oacontent"]').hide();
                $(document.body).find(contentSel).off().remove();
                $('#oa-shade').css('cursor', 'pointer');
            },
            closeContent: function() {
                var me = this;
                me.removeContent();
            },
            showContent: function(id) {
                var me = this;
                var sel = '#' + id;
                $(document.body).find(sel).show();
                _resizeContent(sel);
                //调整微信位置
                _runPrivateMsgMethod('toMin');
            },
            hideContent: function(id) {
                var me = this;
                $(document.body).find('#' + id).hide();
            },
            popupFinal: function(conf){
                //法1，rk.oa.popupFinal({param: {age: 30, name: 'zl'}, ctrlPath: 'oa/workreport/workreportContent'})
                //法2，rk.oa.popupFinal({param: {age: 30, name: 'zl'}, appName: 'workreport'})
                var url = '/final.action';
                var param = conf.param;
                var ctrlPath = conf.ctrlPath;
                var appName = conf.appName;
                //if(url.indexOf('?') < 0)url = url + '?';
                //if(param){
                //    for(s in param)
                //    url = url + '&' + s + '=' + param[s];
                //}
                //if(ctrlPath)url = url + '&cp=' + ctrlPath;
                //if(appName)url = url + '&a=' + appName;
                //window.open(url, '_blank');
                rk.openWin(url,param,ctrlPath,appName);
            },
            initScreenWidthHandler: function(){
                _repositionOAStuff()
                $(window).scroll(function(){
                    _repositionOAStuff();
                });

                $(window).resize(function() {
                    _repositionOAStuff()
                });
            }
        });
        function handleMinScreenWith(){

        }
        function _repositionOAStuff(){
            var oaPanel = $('#oa_panel');
            var oaContent = $(document.body).find('>[act="oacontent"]:visible');//可能是日程的或普通的content
            var headheight = $('#pagehead').outerHeight();
            //横向滚动条
            {
                var scrollleft = $(window).scrollLeft();

                var screenwidth = $(window).width();
                var offset = document.body.scrollWidth - screenwidth - scrollleft;

                if(oaPanel.is(':visible')){
                    rk.oa.getPanel().css('right', -1 * offset + 'px')
                }
                if(oaContent.is(':visible')){
                    offset = offset - oaPanel.outerWidth();
                    oaContent.css('right', -1 * offset + 'px')
                }
            }
            //纵向滚动条
            {
                var scrolltop = $(window).scrollTop();
                //console.log(document.body.scrollHeight , screenheight , scrolltop)
                var offset = -1*scrolltop + headheight;

                if(oaPanel.is(':visible')){
                    oaPanel.css('top', offset + 'px');
                }
                if(oaContent.is(':visible')){
                    oaContent.css('top', offset + 'px');
                }
            }
            var h = document.body.scrollHeight - headheight;
            var conElem = oaContent.get(0);
            var panElem = oaPanel.get(0);
            if(conElem)conElem.style.height = h + 'px';
            if(panElem)panElem.style.height = h + 'px';
        };
        var _handleCurtainResize = function(panelSel) {
            __resizeCurtain(panelSel);//确保滑出时的效果
            if (curtain_resize_inited) return; //仅需声明一次
            curtain_resize_inited = true;
            $(window).resize(function() {
                //clearTimeout(resize_timer);
                //resize_timer = setTimeout(function(){
                _resizeCurtain(panelSel);
                //}, 1);
            })
        };
        var _resizeCurtain = function(panelSel) {
            var panelCon = $(panelSel);
            var curtain = panelCon.find('>.oa-curtain');
            if(curtain.size() == 0 || !curtain.is(':visible'))return;
            __resizeCurtain(panelSel);
        };
        var __resizeCurtain = function(panelSel) {
            var panelCon = $(panelSel);
            var curtain = panelCon.find('>.oa-curtain');
            var height = panelCon.find('.oa-panel-body').outerHeight(true);
            //偏移top高度
            var topOffset = curtain.data('top');
            topOffset = $.isNumeric(topOffset) ? parseInt(topOffset) : 0;

            curtain.height(height - topOffset);
            if(topOffset > 0){
                var titleHeight = panelCon.find('.oa-panel-header').outerHeight();
                curtain.css('top', (titleHeight + topOffset)+'px');
            }
        };
        var _handleContentResize = function(sel) {
            var me = this;
            if (content_resize_inited) return; //仅需声明一次
            content_resize_inited = true;
            $(window).resize(function() {
                //clearTimeout(resize_timer);
                //resize_timer = setTimeout(function(){
                _resizeContent(sel);
                //}, 1);
            })
        };
        var _resizeContent = function(sel) {
            var elem = $(sel);
            if(elem.size() == 0 || !elem.is(':visible'))return;
            var panel = rk.oa.getPanel();
            var w = $(window).width() - 540;
            //var h = $(window).height() - parseInt($(sel).css('top')); //$('#pagehead').outerHeight(true);
            // elem.width(w);
            var paddings = parseInt($(sel).css('padding-bottom')) + parseInt($(sel).css('padding-top'));
            // h = h - paddings;
            // $(sel).height(h);
            $(sel).updateScroll();

            //当空间不够时，应当收折左侧菜单
            if($('#pageleft_fold').is(':visible'))return; //已经收折了
            var leftmenu = $('#pageleft_unfold').is(':visible') ? $('#pageleft_unfold') : $('#pageleft_fold');

            var body_width = $(document.body).innerWidth();
            var panel_width = rk.oa.getPanel().outerWidth();
            var content_width = rk.oa.getContent().outerWidth();
            var leftmenu_width = leftmenu.outerWidth();
            var restWidth = body_width - panel_width - content_width - leftmenu_width;

            if(restWidth < 0){
                rk.foldLeftMenu();
            }
        };
        var _runPrivateMsgMethod = function(fnName, param){
                if($('#privaemsg').data('msgInited') === 'privatemsginited'){
                    $('#privatemsg').privateMsgCtrl(fnName, param);
                }else{
                    require.async(['page/js/privatemsg/privateMsgCtrl'],function(){
                        $('#privatemsg').privateMsgCtrl();
                        $('#privatemsg').privateMsgCtrl(fnName, param);
                    });
                }
        }
    })();
    module.exports = rk;
});
